package net.hn.hnms.biz.upkafka.config;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class ResourceExtractor {

    private Path tempDir;

    // 在项目启动时执行
    @PostConstruct
    public void init() throws IOException {
        String dirName = "myKafKaAppResources";

        // 获取系统临时目录
        Path tempDirPath = Paths.get(System.getProperty("java.io.tmpdir"), dirName);

        // 如果目录已存在，先删除
        if (Files.exists(tempDirPath)) {
            deleteDirectory(tempDirPath);
            System.out.println("Deleted existing directory: " + tempDirPath.toAbsolutePath());
        }

        // 创建新的临时目录会带一个随机数，并将其赋值给 tempDir
//        tempDir = Files.createTempDirectory(tempDirPath.getParent(), dirName);
        tempDir = tempDirPath;

        Files.createDirectories(tempDir);  // 确保使用固定名称的目录
        System.out.println("Temporary directory created at: " + tempDir.toAbsolutePath());

        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            // windows路径下
            // 使用 icacls 命令设置权限
            String command = "icacls " + tempDirPath + " /grant Everyone:(F)";
            Process process = Runtime.getRuntime().exec(command);
            // 等待命令执行完毕
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("权限设置成功: " + tempDirPath);
        } else if (osName.contains("nux") || osName.contains("nix")) {
            // 指定文件夹路径
            // 设置目录权限为 755 (rwxr-xr-x)
            Set<PosixFilePermission> perms = new HashSet<>();
            perms.add(PosixFilePermission.OWNER_READ);
            perms.add(PosixFilePermission.OWNER_WRITE);
            perms.add(PosixFilePermission.OWNER_EXECUTE);

            perms.add(PosixFilePermission.GROUP_READ);
            perms.add(PosixFilePermission.GROUP_EXECUTE);

            perms.add(PosixFilePermission.OTHERS_READ);
            perms.add(PosixFilePermission.OTHERS_EXECUTE);

            Files.setPosixFilePermissions(tempDirPath, perms);
            System.out.println("权限设置成功: " + tempDirPath);
        }

        // 定义需要复制的资源文件
        List<String> resourcesToExtract = new ArrayList<>();
        resourcesToExtract.add("kafkaSecurityMode");
        resourcesToExtract.add("krb5.conf");
        resourcesToExtract.add("client.properties");
        resourcesToExtract.add("connect-distributed.properties");
        resourcesToExtract.add("connect-standalone.properties");
        resourcesToExtract.add("producer.properties");
        resourcesToExtract.add("server.properties");
        resourcesToExtract.add("mine.properties");
//        resourcesToExtract.add("user.keytab");

        // 复制资源文件到临时目录
        for (String resourcePath : resourcesToExtract) {
            extractResourceToTempDir(resourcePath);
        }

        // 打印临时目录路径
        System.out.println("Resources copied to: " + tempDir.toAbsolutePath());
    }

    // 递归删除目录及其内容
    private static void deleteDirectory(Path path) throws IOException {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file); // 删除文件
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir); // 删除目录
                return FileVisitResult.CONTINUE;
            }
        });
    }

    private void extractResourceToTempDir(String resourcePath) throws IOException {
        ClassPathResource resource = new ClassPathResource(resourcePath);
        if (resource.exists()) {
            // 创建目标文件
            File tempFile = new File(tempDir.toFile(), resourcePath);

            // 创建输入流读取资源
            try (InputStream inputStream = resource.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(tempFile)) {

                // 复制文件
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        } else {
            System.out.println("Resource not found: " + resourcePath);
        }
    }

    // 获取临时目录的路径，供其他类使用
    public Path getTempDir() {
        return tempDir;
    }
}
